package edu.ccut.titan.tag.report.servlet;


import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;

import javax.swing.JOptionPane;

import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.util.JRLoader;

public class PrinterApplet extends javax.swing.JApplet {

	private static final long serialVersionUID = 7699126300026646174L;

	private URL url = null;

	private JasperPrint jasperPrint = null;

	public PrinterApplet() {
	}

	public void init() {
		String strUrl = getParameter("REPORT_URL");

		if (strUrl != null) {
			try {
				url = new URL(super.getCodeBase(), strUrl);
			} catch (Exception e) {
				StringWriter swriter = new StringWriter();
				PrintWriter pwriter = new PrintWriter(swriter);
				e.printStackTrace(pwriter);
				JOptionPane.showMessageDialog(this, swriter.toString());
			}
		} else {
			JOptionPane.showMessageDialog(this, "Source URL not specified");
		}
	}

	public void print() {
		if (url == null) {
			JOptionPane.showMessageDialog(this, "Source URL not specified");
			return;
		}

		if (jasperPrint == null) {
			try {
				//JOptionPane.showMessageDialog(this, url.toString());
				jasperPrint = (JasperPrint) JRLoader.loadObject(url);
			} catch (Exception e) {
				StringWriter swriter = new StringWriter();
				PrintWriter pwriter = new PrintWriter(swriter);
				e.printStackTrace(pwriter);
				JOptionPane.showMessageDialog(this, swriter.toString());
			}
		}

		if (jasperPrint != null) {
			final JasperPrint print = jasperPrint;

			Thread thread = new Thread(new Runnable() {
				public void run() {
					try {
						JasperPrintManager.printReport(print, true);
					} catch (Exception e) {
						StringWriter swriter = new StringWriter();
						PrintWriter pwriter = new PrintWriter(swriter);
						e.printStackTrace(pwriter);
						JOptionPane.showMessageDialog(null, swriter.toString());
					}
				}
			});

			thread.start();
		} else {
			JOptionPane.showMessageDialog(this, "Empty report.");
		}
	}
}
